package helper

import (
	"bytes"
	"encoding/binary"
	"errors"
)

//ToBytes 将数据按照指定字节序转换成字节数组
func ToBytes(order binary.ByteOrder, v ...interface{}) ([]byte, error) {
	if len(v) == 0 {
		return nil, errors.New("to bytes fail, no enough param v")
	}

	buf := new(bytes.Buffer)
	for i := 0; i < len(v); i++ {
		if v[i] == nil {
			continue
		}
		err := binary.Write(buf, order, v[i])
		if err != nil {

			return nil, err
		}
	}

	return buf.Bytes(), nil
}

//IntToBytes 将int型值转换为指定长度的byte切片，len不应该超过8 高位在前
func IntToBytes(source, len int) []byte {
	target := make([]byte, len)

	for i := 0; i < len; i++ {
		target[i] = byte(uint64(source) >> ((len - i - 1) * 8))
	}

	return target
}

//BytesToInt 将byte切片转换成int
func BytesToInt(source []byte) int {
	var target int

	for i := 0; i < len(source); i++ {
		target = target | int(source[i])<<((len(source)-i-1)*8)
	}

	return target
}

//RevertString 按照指定的rune数量作为一个单元进行翻转
func RevertString(source string, unitLen int) string {
	//左右指针方法处理
	sr := []rune(source)
	var left, right = 0, len(sr) - 1
	for {
		if right-left < unitLen {
			break
		}
		for i := 0; i < unitLen; i++ {
			sr[left+i], sr[right-unitLen+1+i] = sr[right-unitLen+1+i], sr[left+i]
		}
		left += unitLen
		right -= unitLen
	}
	return string(sr)
}
